package com.example.service;

import com.example.mapper.HrMapper;
import com.example.mapper.HrRoleMapper;
import com.example.model.Hr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 创建人: 麦健豪
 * 创建日期: 2020/9/17 23:07
 */
@Service
public class HrService implements UserDetailsService {

    @Autowired
    HrMapper hrMapper;
    @Autowired
    HrRoleMapper hrRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Hr hr = hrMapper.findUserByUsername(username);
        if (hr == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        hr.setRoles(hrMapper.getHrRolesByHrId(hr.getId()));
        return hr;
    }

    public List<Hr> getAllHrs(String keywords) {
        //获取当前用户id
        Integer hrid = ((Hr) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        return hrMapper.getAllHrs(hrid, keywords);
    }

    public Integer updateHr(Hr hr) {
        return hrMapper.updateByPrimaryKeySelective(hr);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean updateHrRole(Integer hrid, Integer[] rids) {
        //先全部删除，再全部添加
        hrRoleMapper.deleteByHrid(hrid);
        if (rids.length == 0) {
            //rids为空,只需执行上面删除步骤,无需添加
            return true;
        } else {
            return hrRoleMapper.addRole(hrid, rids) == rids.length;
        }
    }

    public Integer deleteHrById(Integer id) {
        return hrMapper.deleteByPrimaryKey(id);
    }

    public boolean updateHrPasswd(String oldpass, String pass, Integer hrid) {
        Hr hr = hrMapper.selectByPrimaryKey(hrid);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //验证原密码
        if (encoder.matches(oldpass, hr.getPassword())) {
            String encodePass = encoder.encode(pass);
            Integer result = hrMapper.updatePasswd(hrid, encodePass);
            if (result == 1) {
                return true;
            }
        }
        return false;

    }

    public Integer updateUserface(String url, Integer id) {
        return hrMapper.updateUserface(url, id);
    }
}
